//扫描指定⽬录，并找到名称或者内容中包含指定字符的所有普通⽂件（不包含⽬录）

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(System.in);

        System.out.println("输入文件名中的关键字");
        String keyWord = scanner.next();

        System.out.println("输入指定的目录");
        String dir = scanner.next();
        File dirFile = new File(dir);

        if (!dirFile.exists()) {
            System.out.println("输入的目录不存在");
            return;
        }

        if (!dirFile.isDirectory()) {
            System.out.println("输入的目录非法");
            return;
        }

        List<File> ret = new ArrayList<>();//存放含有关键字的文件

        scanDir(dirFile, keyWord, ret);

        int fileNums = ret.size();
        if (fileNums == 0) {
            System.out.println("未找到符合条件的文件");
        }
        for (int i = 0; i < fileNums; i++) {
            System.out.println(ret.get(i).getAbsoluteFile());
        }
    }

    private static void scanDir(File dirFile, String keyWord, List<File> ret) throws FileNotFoundException {
        File[] files = dirFile.listFiles();//存放dirFile下的子文件

        if (files == null || files.length == 0) {
            return;
        }

        for (File file : files) {
            if (file.isDirectory()) {//file是目录，递归
                scanDir(file, keyWord, ret);
            } else {
                //现判断文件名中是否含有关键字
                if (file.getName().contains(keyWord)) {
                    ret.add(file.getAbsoluteFile());
                } else {
                    //判断文件中是否含有关键字
                    if (scanFile(file, keyWord)) {
                        ret.add(file.getAbsoluteFile());
                    }
                }
            }
        }
    }

    private static boolean scanFile(File file, String keyWord) throws FileNotFoundException {//查找文件中是否含有关键字
        //读汉字或字符
        StringBuilder stringBuilder = new StringBuilder();
        try(InputStream inputStream = new FileInputStream(file)) {
            try(Scanner read = new Scanner(inputStream, StandardCharsets.UTF_8)) {
                while (read.hasNext()) {
                    stringBuilder.append(read.next());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return stringBuilder.indexOf(keyWord) != -1;
    }

    
}
